import Taro from "@tarojs/taro";

const USER_ID_KEY = "tz_userId"; //uid
const TOKEN_KEY = "tz_token"; //token
const TOKEN_INFO_KEY = "tz_token_info"; //token_info
const USER_INFO_KEY = "tz_user_info"; //用户信息
const DICT_MAP_KEY = "tz_dict_map"; //数据字典
const COLD_COMPANY = "tz_cold_company"; // 冷链数据

// 设置UserToken
export function setToken(token) {
  return set(TOKEN_KEY, token);
}

// 设置 UserTokenInfo
export function setTokenInfo(data) {
  data.now = Date.now();
  return set(TOKEN_INFO_KEY, data);
}

// 设置UserId
export function setUserId(id) {
  set(USER_ID_KEY, id);
}

// 设置userInfo
export function setUserInfo(userInfo) {
  const { userType: _userType } = userInfo;
  if (Number.isInteger(parseInt(_userType, 10))) {
    userInfo.userType = {
      isPersonal: _userType === "1", //个人版
      isDriver: _userType === "2", //司机
      isOperator: _userType === "0", //操作员
      value: _userType,
    };
  }

  set(USER_INFO_KEY, userInfo);
}

// 设置 coldCompany
export function setColdCompany(coldCompany) {
  set(COLD_COMPANY, coldCompany);
}

/* *************************** get ********************************** */

//获取Token
export function getToken() {
  return get(TOKEN_KEY);
}

//获取Token_info
export function getTokenInfo() {
  return get(TOKEN_INFO_KEY);
}

//获取 USER_ID
export function getUserId() {
  return get(USER_ID_KEY);
}

//获取 USER_Info
export function getUserInfo() {
  return get(USER_INFO_KEY);
}

//设置数据字典 dicMap
export function setDicMap(dicMap) {
  return set(DICT_MAP_KEY, dicMap);
}
//获取数据字典 dicMap
export function getDicMap() {
  return get(DICT_MAP_KEY);
}

//获取 coldCompany
export function getColdCompany() {
  return get(COLD_COMPANY);
}

/* ****************************** remove ******************************* */

// 删除token
export function removeToken() {
  remove(TOKEN_KEY);
}

// 删除token_info
export function removeTokenInfo() {
  remove(TOKEN_INFO_KEY);
}

// 删除UID
export function removeUserId() {
  remove(USER_ID_KEY);
}
// 删除UINFO
export function removeUserInfo() {
  remove(USER_INFO_KEY);
}

/* ****************************** 包装方法 ******************************* */

export function set(key, content) {
  return Taro.setStorage({ key, data: content });
}

export function get(key) {
  let info = undefined;
  try {
    info = Taro.getStorageSync(key);
    return info;
  } catch (error) {
    return info;
  }
}
export function remove(key) {
  Taro.removeStorage(key);
}
export function clear() {
  Taro.clearStorage();
}

export default {
  setToken,
  getToken,
  removeToken,
  setUserId,
  getUserId,
  removeUserId,
  setUserInfo,
  getUserInfo,
  removeUserInfo,
  set,
  get,
  remove,
  clear,
};
